// @flow
import React from 'react'
import { Route } from 'react-router-dom'
import Sidebar from 'containers/SidebarContainer'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import Bom from './Bom'
import ModelView from './ModelView'
import Condition from './Condition'
import Customer from './Customer'
import Malfunction from './Malfunction'
import Overview from './Overview'
import Resume from './Resume'
import Service from './Service'
import Wheel from 'components/Wheel'
import ModelDetailView from 'components/ModelDetailView'
import styles from './DeviceFile.css'
import Moment from 'moment'
import { withRouter } from 'react-router'
import { connect } from 'react-redux'

type Props = {
  match: Object,
  history: Object,
  deviceCard: Object
}
class DeviceFile extends React.Component {
  props: Props
  goToCustomer: Function
  constructor (props: Object) {
    super(props)
    this.goToCustomer = this.goToCustomer.bind(this)
  }
  goToCustomer () {
    const deviceData = this.props.deviceCard.deviceData
    const { history } = this.props
    universalFetch(`${__SERVICE_API__}device/customers/${deviceData.customerId}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const result = json.result
        const location = {
          pathname: '/device-card',
          state: {
            data: result,
            groupId: result.id,
            groupName: result.name,
            longitude: result.region.longitude,
            latitude: result.region.latitude,
            count: result.count
          }
        }
        history.push(location)
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  render () {
    const props = this.props
    const deviceData = this.props.deviceCard.deviceData
    const deviceNo = this.props.deviceCard.deviceData.deviceNo
    const deviceFields = [
      ['设备名称', deviceData.name],
      // ['设备编号', deviceData.deviceNo],
      ['客户名称', deviceData.customerName],
      ['设备型号', deviceData.spec],
      ['设备类型', deviceData.type],
      ['类型编号', deviceData.typeEn],
      ['投运日期', deviceData.operationDate
        ? Moment(deviceData.operationDate, 'YYYY-MM-DDThh:mm:ssSSSZ').format('YYYY-MM-DD') : ''],
      ['设备状态', deviceData.status],
      ['生产日期', deviceData.produceDate
        ? Moment(deviceData.produceDate, 'YYYY-MM-DDThh:mm:ssSSSZ').format('YYYY-MM-DD') : ''],
      // ['最近维修时间', Moment(deviceData.latestRepairDate, 'YYYY-MM-DDThh:mm:ssSSSZ').format('YYYY-MM-DD hh:mm:ss')],
      ['负责人', deviceData.owner]
    ]
    const imageUrl = deviceData.imageUrl || '/wheel/wheel.png'
    return (
      <div style={{ height: '100%' }}>
        <Sidebar id='deviceFile' style={{ width: '320px',
          background: '#f5f5f5'
        }} type='float'>
          <div className={styles['title']}>设备概况</div>
          <section className={styles['section']}>
            <table width='100%'><tbody>
              {
                deviceFields.map((field, i) => {
                  if (i === 1) {
                    return (
                      <tr key={i}>
                        <td style={{ color:'#999' }}><div>{field[0]}</div></td>
                        <td style={{ color:'#49a9ee' }}>
                          <div style={{ cursor: 'pointer' }}
                            onClick={this.goToCustomer} title={field[1]}>{field[1]}</div>
                        </td>
                      </tr>
                    )
                  } else {
                    return (
                      <tr key={i}>
                        <td style={{ color:'#999' }}><div>{field[0]}</div></td>
                        <td style={{ color:'#333' }}><div title={field[1]}>{field[1]}</div></td>
                      </tr>
                    )
                  }
                })
              }
            </tbody></table>
          </section>
          <section className={styles['wheel-container']}>
            {
              <label className={styles['wheelLabel']}>{deviceData.deviceNo}</label>
            }
            <img className={styles['wheelImgBg']} src='/wheel/wheelBg.png' />
            <img className={styles['wheelImg']} src={imageUrl} />
            <Wheel imageUrl={imageUrl} base={props.match.url} name={deviceNo} history={this.props.history} />
          </section>
        </Sidebar>
        <Route path={`${props.match.url}/bom`} component={Bom} />
        <Route path={`${props.match.url}/model`} component={ModelView} />
        <Route path={`${props.match.url}/condition`} component={Condition} />
        <Route path={`${props.match.url}/customer`} component={Customer} exact />
        <Route path={`${props.match.url}/malfunction`} component={Malfunction} />
        <Route path={`${props.match.url}/overview`} component={Overview} />
        <Route path={`${props.match.url}/resume`} component={Resume} />
        <Route path={`${props.match.url}/service`} component={Service} />
        <Route path={`${props.match.url}/models/:id`} component={ModelDetailView} />
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    deviceCard: state.deviceCard
  }
}
export default connect(mapStatesToProps, {})(withRouter(DeviceFile))
